package com.copsoftware.mantenimientos.testigo.service;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.BeanUtils;

import com.copsoftware.entity.DenTestigoImpl;
import com.copsoftware.hibernate.cfg.HibernateUtils;
import com.copsoftware.mantenimientos.testigo.beans.Testigo;
import com.copsoftware.mantenimientos.testigo.dao.TestigoDAO;

public class TestigoService {

	
	public void guardarTestigo(Testigo testigo) throws Exception {
		DenTestigoImpl denTestigo = getTestigo(testigo.getCPersona());
		
		BeanUtils.copyProperties(testigo, denTestigo);
		
		Session session = HibernateUtils.getSessionFactory()
		.getCurrentSession();
		Transaction tx = null;
	
		try {
			tx = session.beginTransaction();
			TestigoDAO testigoDAO = new TestigoDAO();
			testigoDAO.setSession(session);
			testigoDAO.guardarTestigo(denTestigo);
			
			tx.commit();
			
			BeanUtils.copyProperties(denTestigo, testigo);
		}catch (Exception e) {
			// TODO Auto-generated catch block
			tx.rollback();
		}
	}
	
	private DenTestigoImpl getTestigo(Integer cTestigo) {
		DenTestigoImpl denTestigo = null;
		if (cTestigo == null) {
			denTestigo = new DenTestigoImpl();
		} else {
			denTestigo = buscarTestigo(cTestigo);
		}
		return denTestigo;
	}
	
	private DenTestigoImpl buscarTestigo(Integer cTestigo) {

		Session session = HibernateUtils.getSessionFactory()
				.getCurrentSession();
		Transaction tx = null;
		DenTestigoImpl testigo = null;
		try {
			tx = session.beginTransaction();
			TestigoDAO testigoDAO = new TestigoDAO();
			testigoDAO.setSession(session);
			testigo = testigoDAO.buscarTestigo(cTestigo);
			tx.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			tx.rollback();
		}
		return testigo;

	}
	
	public void buscarTestigo(Testigo testigo)
	{
		DenTestigoImpl denTestigo = getTestigo(testigo.getCPersona());
		BeanUtils.copyProperties(denTestigo, testigo);
		
	}
	
}
